package jacktgq.fractalImage.vicsek;

import jacktgq.AlgoVisHelper;

import javax.swing.*;
import java.awt.*;

public class AlgoFrame extends JFrame{
    private int canvasWidth;
    private int canvasHeight;

    private FractalData fractalData;
    public AlgoCanvas canvas;

    public AlgoFrame(String title, int width, int height, FractalData fractalData){
        super(title);
        this.canvasWidth = width;
        this.canvasHeight = height;
        this.fractalData = fractalData;

        canvas = new AlgoCanvas();
        setContentPane(canvas);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //setSize(width + 16, height + 39);
        setSize(width + 6, height + 29);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void render(FractalData fractalData) {
        this.fractalData = fractalData;
        canvas.repaint();
    }

    public class AlgoCanvas extends JPanel {
        public AlgoCanvas() {
            // 双缓存
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            // 抗锯齿
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);
            // 具体绘制
            drawFractal(g2d, 0, 0, canvasWidth, canvasHeight, 0);
        }

        private void drawFractal(Graphics2D g2d, int x, int y, int w, int h, int depth) {
            if (depth == fractalData.getDepth()) {
                AlgoVisHelper.setColor(g2d, AlgoVisHelper.Indigo);
                AlgoVisHelper.fillRectangle(g2d, x, y , w, h);
                return;
            }

            if (w <= 1 || h <= 1) {
                AlgoVisHelper.setColor(g2d, AlgoVisHelper.Indigo);
                AlgoVisHelper.fillRectangle(g2d, x, y , Math.max(w, 1), Math.max(h, 1));
            }
            int w_3 = w / 3;
            int h_3 = h / 3;
            drawFractal(g2d, x, y, w_3, h_3, depth + 1);
            drawFractal(g2d, x + 2 * w_3, y, w_3, h_3, depth + 1);
            drawFractal(g2d, x + w_3, y + h_3, w_3, h_3, depth + 1);
            drawFractal(g2d, x, y + h_3 * 2, w_3, h_3, depth + 1);
            drawFractal(g2d, x + w_3 * 2, y + h_3 * 2, w_3, h_3, depth + 1);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(canvasWidth, canvasHeight);
        }
    }
}


